
/**
 * 
 * @param {element} el 动画元素
 * @param {Array} classList 要添加的类名
 */
function addAnimate(el,classList = []){
    // if(!classList.length) return console.warn('样式类数组为空.')
    !classList.length && (classList = el.dataset.animate.split(','))
    console.log(classList);
    el.addEventListener('animationend',function(){
        const classStr = this.className;
        if(classStr.includes(classList[1])){
            this.className = classStr.replace(/animate__\w+/g,'')
        }else{
            this.classList.add(classList[1])
        }
    });
    el.style.opacity = 1;
    el.classList.add('animate__animated',classList[0])
}
/**
 * 
 * @param {Object} config 配置对象
 * @param {Function} callback 回调函数
 */
function observerHandler(config={},callback){
    const els = config.els;
    const threshold = config.threshold;
    const observer = new IntersectionObserver(fn, {threshold :threshold});
    function fn(ele){
        ele.forEach(i=>{
            if(i.intersectionRatio > 0 || i.isIntersecting){
                callback(i.target)
                observer.unobserve(i.target)
            }
        })
    };
    els.forEach(i=>observer.observe(i))
};

/**
 * 
 * @param {Object} config 配置对象
 * @param {Function} callback 回调函数
 */
function lazyLoad(config={},callback){
    const els = config.els;
    function getTop(el){
        let t = el.offsetTop;
        while(el = el.offsetParent){
            t += el.offsetTop;
        }
        return t;
    }
    function loop(){
        const S = document.documentElement.scrollTop || document.body.scrollTop;
        const vh = document.documentElement.clientHeight;
        els.forEach(i=>{
            if((S+vh) >= getTop(i)){
                callback(i)
            }
        })
    }
    loop()
    let oldDate = Date.now();
    return ()=>{
        if(Date.now() - oldDate < 100) return;
        loop()
        oldDate = Date.now();
    }
    
};
/**
 * 
 * @param {Object} config 配置对象
 * @param {Function} callback 回调函数
 */
function Observer(config={},callback){
    if(!config.els.length) return console.warn('元素数组为空');
    config.threshold || (config.threshold = 0);
    config.els.forEach(i=>{
        i.classList.add('animate__animated');
        i.style.visibility = 'hidden';
    });
    if(window.IntersectionObserver){
        return observerHandler(config,callback)
    }else{
        let lazyLoadCopy = lazyLoad(config,callback);
        window.addEventListener('scroll',lazyLoadCopy)
        return lazyLoadCopy;
    }
}
// export {
//     addAnimate,
//     observerHandler,
//     lazyLoad,
//     Observer
// }